<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>5%下跌加仓策略计算器（移动端适配）</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
        }
        body {
            padding: 15px;
            background-color: #f5f5f5;
            -webkit-tap-highlight-color: transparent;
        }
        .container {
            width: 100%;
            background: white;
            padding: 20px 15px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        }
        h1 {
            text-align: center;
            color: #333;
            font-size: 20px;
            margin-bottom: 25px;
            font-weight: 600;
        }
        .params {
            display: flex;
            flex-direction: column;
            gap: 18px;
            margin-bottom: 25px;
            padding: 15px;
            background: #fafafa;
            border-radius: 8px;
        }
        .param-item {
            width: 100%;
        }
        label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: #555;
            font-size: 15px;
        }
        input {
            width: 100%;
            padding: 14px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            background: white;
            -webkit-appearance: none;
            appearance: none;
        }
        input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.1);
        }
        button {
            width: 100%;
            padding: 16px;
            background: #2c3e50;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 17px;
            cursor: pointer;
            margin-top: 8px;
            font-weight: 500;
        }
        button:hover {
            background: #34495e;
        }
        /* 表格横向滚动容器 */
        .table-container {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            margin-top: 20px;
            padding-bottom: 10px;
        }
        table {
            min-width: 800px; /* 保证表格最小宽度，触发横向滚动 */
            border-collapse: collapse;
        }
        th, td {
            padding: 13px 8px;
            text-align: center;
            border: 1px solid #ddd;
            font-size: 14px;
        }
        th {
            background: #3498db;
            color: white;
            font-weight: 500;
            white-space: nowrap;
        }
        td {
            white-space: nowrap;
        }
        tr:nth-child(even) {
            background: #f9f9f9;
        }
        tr:hover {
            background: #f1f1f1;
        }
        .negative {
            color: #e74c3c;
            font-weight: 500;
        }
        .positive {
            color: #27ae60;
            font-weight: 500;
        }
        /* 适配小屏手机的输入框样式 */
        @media (max-width: 320px) {
            h1 {
                font-size: 18px;
            }
            input {
                padding: 12px;
                font-size: 15px;
            }
            button {
                padding: 14px;
                font-size: 16px;
            }
            th, td {
                padding: 11px 6px;
                font-size: 13px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>5%下跌加仓策略计算器</h1>

        <!-- 参数设置区域（纵向排列，适配移动端） -->
        <div class="params">
            <div class="param-item">
                <label for="initialPrice">初始价格（元）</label>
                <input type="number" id="initialPrice" value="2.37" step="0.01" min="0.01">
            </div>
            <div class="param-item">
                <label for="addShares">每次加仓份数（份）</label>
                <input type="number" id="addShares" value="1" step="1" min="1">
            </div>
            <div class="param-item">
                <label for="downPercent">每次下跌比例（%）</label>
                <input type="number" id="downPercent" value="5" step="0.1" min="0.1" max="100">
            </div>
            <div class="param-item">
                <label for="downTimes">下跌次数（次）</label>
                <input type="number" id="downTimes" value="10" step="1" min="1" max="50">
            </div>
            <button onclick="calculateStrategy()">计算策略清单</button>
        </div>

        <!-- 表格横向滚动容器（核心适配移动端） -->
        <div class="table-container">
            <table id="strategyTable">
                <thead>
                    <tr>
                        <th>阶段</th>
                        <th>当前价格（元）</th>
                        <th>累计持仓（份）</th>
                        <th>累计投入成本（元）</th>
                        <th>持有成本（均价，元）</th>
                        <th>持有收益率</th>
                        <th>单次跌幅</th>
                        <th>累计跌幅</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 计算后动态填充 -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        // 计算加仓策略核心函数
        function calculateStrategy() {
            // 获取输入参数
            const initialPrice = parseFloat(document.getElementById('initialPrice').value);
            const addShares = parseInt(document.getElementById('addShares').value);
            const downPercent = parseFloat(document.getElementById('downPercent').value);
            const downTimes = parseInt(document.getElementById('downTimes').value);

            // 验证参数有效性
            if (isNaN(initialPrice) || isNaN(addShares) || isNaN(downPercent) || isNaN(downTimes)) {
                alert('请输入有效的数字参数！');
                return;
            }

            // 初始化数据
            let currentPrice = initialPrice;
            let totalShares = 1;
            let totalCost = initialPrice * 1;
            let avgCost = totalCost / totalShares;
            let holdingReturn = 0;
            let totalDrop = 0;

            // 获取表格 tbody 元素
            const tableBody = document.getElementById('strategyTable').querySelector('tbody');
            tableBody.innerHTML = ''; // 清空原有内容

            // 添加初始持仓行
            addTableRow({
                stage: '初始持仓',
                price: currentPrice.toFixed(2),
                shares: totalShares,
                cost: totalCost.toFixed(2),
                avgCost: avgCost.toFixed(2),
                returnRate: '0.00%',
                singleDrop: '-',
                totalDrop: '0.00%'
            });

            // 循环计算每次下跌加仓数据
            for (let i = 1; i <= downTimes; i++) {
                const lastPrice = currentPrice;
                // 计算本次下跌后价格
                currentPrice = lastPrice * (1 - downPercent / 100);
                // 更新累计数据
                totalShares += addShares;
                const addCost = currentPrice * addShares;
                totalCost += addCost;
                avgCost = totalCost / totalShares;
                // 计算收益率和跌幅
                const totalMarketValue = currentPrice * totalShares;
                holdingReturn = (totalMarketValue - totalCost) / totalCost * 100;
                const singleDrop = (currentPrice - lastPrice) / lastPrice * 100;
                totalDrop = (currentPrice - initialPrice) / initialPrice * 100;

                // 添加本次下跌行
                addTableRow({
                    stage: `第${i}次下跌`,
                    price: currentPrice.toFixed(2),
                    shares: totalShares,
                    cost: totalCost.toFixed(2),
                    avgCost: avgCost.toFixed(2),
                    returnRate: holdingReturn.toFixed(2) + '%',
                    singleDrop: singleDrop.toFixed(2) + '%',
                    totalDrop: totalDrop.toFixed(2) + '%'
                });
            }
        }

        // 向表格添加一行数据
        function addTableRow(data) {
            const tableBody = document.getElementById('strategyTable').querySelector('tbody');
            const row = document.createElement('tr');

            // 遍历数据创建单元格
            Object.values(data).forEach((value, index) => {
                const cell = document.createElement('td');
                cell.textContent = value;
                // 收益率、跌幅列添加颜色标记
                if (index >= 5 && value !== '-') {
                    const num = parseFloat(value);
                    cell.className = num < 0 ? 'negative' : 'positive';
                }
                row.appendChild(cell);
            });

            tableBody.appendChild(row);
        }

        // 页面加载时自动计算一次
        window.onload = calculateStrategy;
    </script>
</body>
</html>